import { Component, OnInit } from '@angular/core';
import { DialogService } from 'app/shared/dialog';
import { NotificationService } from 'app/shared/service';
import { Subject } from 'rxjs';
import { UserManagementService } from '../user-management.service';
import { HttpClient } from '@angular/common/http';
import { FormGroup } from '@angular/forms';
import { PublicService } from 'app/public/public.service';
import { differenceInCalendarDays } from 'date-fns';

import * as moment from 'moment';

declare const Add: any;
declare const Delete: any;

@Component({
    selector: 'itmp-manage-users',
    templateUrl: './manage-users.component.html',
    styleUrls: ['./manage-users.component.css']
})
export class ManageUsersComponent implements OnInit {
    search$ = new Subject<object>();
    selectedValue = 'All';
    isVisible = false;
    isOkLoading = false;
    selectedUser = null; // 每行tr的数据
    addUserTitle: string;
    isDeleteLoading = false;
    totalEle = 0;
    data = '';
    userId = '';
    optionList = [
        { label: 'All', value: 'all' },
        { label: 'Administor', value: 'administor' },
        { label: 'Operator', value: 'operator' },
        { label: 'Supervisor', value: 'supervisor' }
    ];
    // optionList = null;
    // 筛选框下拉列表
    selectionList = {
        Role: ['Administrator', 'Operator', 'Supervisor']
    };
    // pagination: any; // 分页数据的对象
    searchData: any; // 搜索数据的对象
    listOfData = []; // 列表数据的数组
    renderHeader = null; // 表头数据的数组
    roleOptions = []; // role下拉框
    listOfOption = []; // organization下拉框
    // 右上角的打印，放大等按钮
    toolbarList = [{ className: 'icon-dayinfuyin-' }];
    dateRange = [];
    dateUpRange = [];
    roleSelect = null;
    orgSelect = null;
    queryStartTime = null;
    queryEndTime = null;
    queryUpStartTime = null;
    queryUpEndTime = null;
    queryName = null;
    createTime = '';
    // 分页数据的对象
    pagination = {
        totalEle: 25,
        currentPage: 1,
        currentSize: 10,
        pageSize: 10
    };
    userInfoForm: FormGroup;
    accessButton = {
        Create: false,
        Edit: false,
        Delete: false,
        PRINT: false
    };
    zoneAssignment = [];
    selectZoneAssignment = [];
    constructor(
        private dialog: DialogService,
        private message: NotificationService,
        private http: HttpClient,
        private UMService: UserManagementService,
        private pub: PublicService
    ) {}

    ngOnInit() {
        this.renderHeader = [
            {
                name: 'Name',
                key: null,
                value: 'name',
                isChecked: true
            },
            // {
            //     name: 'Password',
            //     key: null,
            //     value: 'password',
            //     isChecked: true
            // },
            {
                name: 'Role',
                key: null,
                value: 'role',
                isChecked: true
            },
            {
                name: 'CreateDate',
                key: null,
                value: 'createDate',
                isChecked: true
            },
            {
                name: 'UpdateDate',
                key: null,
                value: 'updateDate',
                isChecked: true
            },
            {
                name: 'Organization',
                key: null,
                value: 'organization',
                isChecked: true
            }
        ];
        // this.getData();
        this.refresh();
        this.getRoad();
        // this.initData();
        this.getButtonAccess();
    }
    getButtonAccess() {
        this.accessButton = this.pub.getButtonAccess('22', this.accessButton);
    }
    // 初始化分页和搜索
    initData() {
        // this.pagination = {
        //     totalEle: 25,
        //     pageSize: 10,
        //     currentPage: 1,
        //     currentSize: 10
        // };
        this.searchData = {
            userId: null,
            user_Name: this.queryName,
            user_Pwd: null,
            organization_Id: this.orgSelect,
            userRole_Id: this.roleSelect,
            createTime: {
                startTime: this.queryStartTime,
                endTime: this.queryEndTime
            },
            updateTime: {
                startTime: this.queryUpStartTime,
                endTime: this.queryUpEndTime
            }
        };
    }
    // 获取数据
    getData() {
        this.selectedUser = null;
        if (this.queryName === '' || this.roleSelect === '' || this.orgSelect === '') {
            this.queryName = null;
            this.roleSelect = null;
            this.orgSelect = null;
        }
        const queryData = {
            condition: {
                userId: null,
                user_Name: this.queryName,
                user_Pwd: null,
                organization_Id: this.orgSelect,
                userRole_Id: this.roleSelect,
                createTime: {
                    startTime: this.queryStartTime,
                    endTime: this.queryEndTime
                },
                updateTime: {
                    startTime: this.queryUpStartTime,
                    endTime: this.queryUpEndTime
                }
            },
            pageNum: this.pagination.currentPage,
            pageSize: this.pagination.pageSize
        };
        const queryData2 = {
            pageSize: 99999,
            pageNum: 1,
            condition: {
                userRole_Id: this.roleSelect,
                createTime: {
                    startTime: this.queryStartTime,
                    endTime: this.queryEndTime
                },
                updateTime: {
                    startTime: this.queryUpStartTime,
                    endTime: this.queryUpEndTime
                },
                roleName: null,
                description: null
            }
        };
        const queryData3 = {
            condition: {
                organization_Id: null,
                organization_Name: null
            },
            pageNum: 1,
            pageSize: 99999
        };
        // 获取manageUser数据
        this.UMService.getAllUser(queryData).subscribe(res => {
            if (res.errCode === '000000') {
                this.listOfData = res.content.content;
                this.pagination.currentPage = res.content.pageNum;
                this.pagination.currentSize = res.content.numberOfElements;
                this.pagination.totalEle = res.content.totolElements;
            }
        });
        // 获取manageRole数据,添加的下拉框需要
        this.UMService.getAllUserRole(queryData2).subscribe(res => {
            if (res.errCode === '000000') {
                this.roleOptions = res.content.content;
            }
        });
        // 获取manageOrganization数据,下拉框需要
        this.UMService.getAllOrganizations(queryData3).subscribe(res => {
            if (res.errCode === '000000') {
                this.listOfOption = res.content.content;
            }
        });
    }
    // 新建或则编辑
    addOrEdit(flag) {
        if (flag === 'add') {
            this.selectZoneAssignment = [];
            this.addUserTitle = 'Add_User';
            // this.cancelActive();
            this.selectedUser = {
                userId: 0,
                user_Name: '',
                user_Pwd: '',
                organization: [],
                userRole: null
            };
            this.isVisible = true;
        } else {
            this.addUserTitle = 'Edit_User';
            if (this.selectedUser && this.selectedUser.userRole !== null) {
                this.isVisible = true;
            } else {
                // 提醒用户未选择要编辑的内容
                this.message.notify({ type: 'warning', path: 'UserManagement.ManageUser.select_notify' });
            }
        }
    }
    // 删除
    delete() {
        this.isDeleteLoading = false;
        if (this.selectedUser) {
            this.dialog
                .confirm({
                    title: 'UserManagement.ManageUser.Delete_Role',
                    content: 'UserManagement.ManageUser.Delete_Content',
                    buttonOkTxt: 'UserManagement.ManageUser.Delete_Save',
                    buttonCancelTxt: 'UserManagement.ManageUser.Delete_Cancel'
                })
                .subscribe(res => {
                    if (res) {
                        this.confirmDelete();
                    } else {
                        this.cancelDelete();
                    }
                });
        } else {
            // 提醒用户未选择要删除的内容
            this.message.notify({ type: 'warning', path: 'UserManagement.ManageUser.delete_notify' });
        }
    }
    // 确认删除
    confirmDelete() {
        const userInfo = {
            createTime: null,
            updateTime: null,
            organization: null,
            userId: this.selectedUser.userId,
            userRole: {
                createTime: null,
                description: null,
                methodAccess: [
                    {
                        methodAccess_Id: null,
                        methodDesc: null,
                        methodName: null,
                        tree_Id: null
                    }
                ],
                roleName: this.selectedUser.roleName,
                userRole_Id: this.selectedUser.userRole
            },
            userZoneRel: this.selectZoneAssignment,
            user_Name: this.selectedUser.user_Name,
            user_Pwd: this.selectedUser.user_Pwd
        };
        // 删除用户
        this.UMService.deleteUserInfo(userInfo).subscribe(
            res => {
                if (res.code === '000000') {
                    this.message.notify({ type: 'success', path: 'UserManagement.ManageUser.deleteSuccess_notify' });
                    this.refresh();
                } else if (res.code === '900007') {
                    this.message.notify({ type: 'warning', path: 'UserManagement.ManageUser.using_user' });
                }
            },
            err => {}
        );
    }
    // 取消删除
    cancelDelete() {}
    // 刷新
    refresh(): void {
        // this.cancelActive();
        // this.initData();
        this.queryStartTime = this.getTimeStamp();
        this.queryEndTime = new Date().getTime();
        this.pagination.currentPage = 1;
        this.pagination.pageSize = 10;
        this.queryStartTime = null;
        this.queryEndTime = null;
        this.queryUpStartTime = null;
        this.queryUpEndTime = null;
        this.queryName = null;
        this.roleSelect = null;
        this.orgSelect = null;
        this.getData();
    }
    // 取消选中
    cancelActive(): void {
        this.selectedUser = null;
        this.listOfData.forEach((data, index) => {
            data.active = false;
        });
    }
    // 点击tr取值
    click(i, item): void {
        this.addUserTitle = 'Edit User';
        this.listOfData.forEach((data, index) => {
            data.active = false;
            if (i === index) {
                // 点击每个tr给与样式active
                data.active = true;
                const obj = {
                    userId: data.userId,
                    organization: data.organization.organization_Name,
                    user_Name: data.user_Name,
                    user_Pwd: data.user_Pwd,
                    userRole: data.userRole.userRole_Id
                };
                this.selectedUser = obj;
                this.createTime = data.createTime;
                this.selectZoneAssignment = data.userZoneRel;
            }
        });
    }
    // 分页控件改变事件
    onPageChange(e) {
        this.pagination.currentPage = e;
        this.getData();
    }
    onSizeChange(e) {
        this.pagination.pageSize = e;
        this.pagination.currentPage = 1;
        this.getData();
    }
    getRoad() {
        this.UMService.getAllEnumInfo().subscribe(res => {
            const data = [];
            if (res.code === '000000') {
                res.data.forEach(ele => {
                    if (ele.category === 'zone') {
                        data.push(ele);
                    }
                });
            }
            data.sort((a, b) => a.value - b.value);
            this.zoneAssignment = data;
        });
    }
    getTimeStamp() {
        const nowdate = new Date();
        nowdate.setMonth(nowdate.getMonth() - 3);
        const y = nowdate.getFullYear();
        const m = nowdate.getMonth() + 1;
        const d = nowdate.getDate();
        const formatwdate = y + '-' + m + '-' + d;
        return new Date(formatwdate).getTime();
    }
    onChange(result: Date): void {
        this.queryStartTime = result[0]
            ? moment(result[0])
                  .startOf('day')
                  .valueOf()
            : null;
        this.queryEndTime = result[1]
            ? moment(result[1])
                  .endOf('day')
                  .valueOf()
            : null;
        this.getData();
    }
    onUpdateChange(result: Date): void {
        this.queryUpStartTime = result[0]
            ? moment(result[0])
                  .startOf('day')
                  .valueOf()
            : null;
        this.queryUpEndTime = result[1]
            ? moment(result[1])
                  .endOf('day')
                  .valueOf()
            : null;
        this.getData();
    }
    onOk(result: Date): void {}

    updateSuccess() {
        this.isVisible = false;
        this.refresh();
    }
    filterSearch() {
        this.pagination.currentPage = 1;
        this.pagination.currentSize = 10;
        this.getData();
    }
    public selectSearch() {
        this.getData();
    }
    public orgSearch() {
        this.getData();
    }
    disabledDate = (current: Date): boolean => {
        // Can not select days before today and today
        return differenceInCalendarDays(current, new Date()) > 0;
    };
}
